package addressBook

import (
	"apiExample/auth"
	"apiExample/common"
	"errors"
	"fmt"
)

type Department struct {
	Id string `json:"id"`
	Name string `json:"name"`
	ParentId string `json:"parentid"`
	UserMember []string `json:"user_member"`
	SubMember []string `json:"sub_member"`
}

type departmentInfoResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	Department *Department `json:"department"`
}

/*
	4.1.1 获取部门详情
 */
func GetDepartmentInfo(id string) (*Department, error) {
	token, err := auth.GetAccessToken()
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/roster/department/get?access_token=%s&department_id=%s", common.ApiUrl, token, id)

	r := &departmentInfoResult{}
	if err := common.HttpGetData(url, r); err != nil {
		return nil, err
	}

	if r.Result != 0 {
		return nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", r.Result, r.Errmsg))
	}

	return r.Department, nil
}

type departmentListResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	Departments []*Department `json:"departments"`
}
/*
	4.1.2 获取部门列表
*/
func GetDepartmentList(id string, fetch int32) ([]*Department, error) {
	token, err := auth.GetAccessToken()
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/roster/department/list?access_token=%s&department_id=%s&fetch_child=%d", common.ApiUrl, token, id, fetch)

	rsp := &departmentListResult{}
	if err := common.HttpGetData(url, rsp); err != nil {
		return nil, err
	}

	if rsp.Result != 0 {
		return nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", rsp.Result, rsp.Errmsg))
	}

	return rsp.Departments, nil
}

type departmentMemberResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	Member []*UserInfo `json:"member"`
}
/*
	4.1.3 获取部门成员
*/
func GetDepartmentMember(id string, fetch int32) ([]*UserInfo, error) {
	token, err := auth.GetAccessToken()
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/roster/department/get_member?access_token=%s&department_id=%s&fetch_child=%d", common.ApiUrl, token, id, fetch)

	r := &departmentMemberResult{}
	if err := common.HttpGetData(url, r); err != nil {
		return nil, err
	}

	if r.Result != 0 {
		return nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", r.Result, r.Errmsg))
	}
	return r.Member, nil
}